package models

import (
	"gitee.com/xuxinzhi2206/corehub/database/mysql"
	"gorm.io/gorm"
	"strconv"
)

type Coupon struct {
	gorm.Model
	UserID           int     `gorm:"type:int(11);comment:用户id"`
	CouponTitle      string  `gorm:"type:varchar(100);comment:优惠卷标题"`
	CouponIntroduce  string  `gorm:"type:varchar(200);comment:优惠卷详情"`
	CouponExpiration string  `gorm:"type:varchar(100);comment:'优惠卷过期时间"`
	CouponStatus     int     `gorm:"type:int(11);comment:优惠卷类型"`
	DiscountValue    float64 `gorm:"type:decimal(10,2);comment:优惠价格"`
}

func (c *Coupon) CouponListShop(userId int, judge bool) (couponList []Coupon, err error) {
	return couponList, mysql.WithMysql(func(db *gorm.DB) error {
		DB := db.Table("coupons").Where("user_id = ?", userId)
		if judge {
			return DB.Where("coupon_status = 2").Find(&couponList).Error
		}
		return DB.Where("coupon_status != 2").Find(&couponList).Error
	})
}

func (c *Coupon) CouponListUser(userId int, couponStatus int) (couponList []Coupon, err error) {
	return couponList, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Table("coupons").Where("user_id = ? and coupon_status = ?", userId, couponStatus).Find(&couponList).Error
	})
}

func (c *Coupon) CouponCreate(userId int64, ruleInfo []Rule) (couponInfo []Coupon, err error) {
	return couponInfo, mysql.WithMysql(func(db *gorm.DB) error {
		for _, v := range ruleInfo {
			couponInfo = append(couponInfo, Coupon{
				Model:            gorm.Model{},
				UserID:           int(userId),
				CouponTitle:      v.Title,
				CouponIntroduce:  v.Introduce,
				CouponExpiration: v.Moment,
				CouponStatus:     2,
				DiscountValue:    v.Price,
			})
		}
		return db.Table("coupons").Create(&couponInfo).Error
	})
}

func (c *Coupon) CouponAdd(userId int64, pointId int64) (couponInfo *Coupon, err error) {
	return couponInfo, mysql.WithMysql(func(db *gorm.DB) error {
		pointsInfo, _ := new(PointsCoupon).PointsCouponInfo(pointId)
		couponInfo = &Coupon{
			UserID:           int(userId),
			CouponIntroduce:  pointsInfo.CouponIntroduce,
			CouponExpiration: strconv.Itoa(pointsInfo.CouponExpiration),
			CouponStatus:     2,
			DiscountValue:    float64(pointsInfo.PointsRequired),
		}
		return db.Table("coupons").Create(&couponInfo).Error
	})
}

func (c *Coupon) CouponInfoByCouponID(couponId int64) (couponInfo *Coupon, err error) {
	return couponInfo, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Table("coupons").Where("coupon_id = ?", couponId).First(&couponInfo).Error
	})
}
